<template>
  <view>
    <h2>进出口系统idaas统一认证页-h5</h2>

    <uni-popup ref="alertDialog" type="dialog">
      <uni-popup-dialog
        type="warn"
        cancelText="关闭"
        confirmText="同意"
        title="提示"
        :content="contain"
        @confirm="dialogConfirm"
        @close="dialogClose"
      ></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { getIdaasConfig } from "@/api/login";
export default {
  name: "MinirabbitIndex",

  data() {
    return {
      code: null,
      contain: "",
      idaas: {
        source: "h5",
        loginUrl:
          "{server}/oauth/authorize?response_type=code&scope=read&client_id={client_id}&redirect_uri={redirect_uri}",
        indexUrl: "{index_server}",
        // 从后端请求的配置
        config: {
          server: null,
          clientId: null,
          redirectUri: null,
          indexServer: null,
        },
      },
    };
  },
  created() {
    // console.log(123);
    // console.log(this.idaas.source);
    this.handleLogin();
  },
  mounted() {},

  methods: {
    dialogConfirm() {
      if (this.isEmpty(this.code)) {
        window.location.href = this.getLoginUrl();
      } else {
        uni.showLoading({
          title: "登录中,请稍后。。。",
        });
        const userInfo = {
          code: this.code,
          source: this.idaas.source,
        };
        this.$store
          .dispatch("loginByIdaasCode", userInfo)
          .then(() => {
            //跳转到首页
            uni.switchTab("/pages/index/index");
            uni.hideLoading();
          })
          .catch((msg) => {
            let message = "请检查授权码是否正确!";
            if (String(msg).indexOf("Invalid authorization code") !== -1) {
              message = "授权码过期,是否跳转到统一认证系统获取授权码";
              uni.showModal({
                title: "提示",
                content: message,
                success: function (res) {
                  if (res.confirm) {
                    window.location.href = this.getLoginUrl();
                  } else if (res.cancel) {
                    console.log("用户点击取消");
                  }
                },
              });
            } else {
              uni.showToast({
                title: message,
                duration: 2000,
                icon: "error",
              });
            }
            loading.close();
          });
      }
    },
    dialogClose() {},
    handleLogin() {
      // 1.获取配置
      getIdaasConfig(this.idaas.source).then((res) => {
        this.idaas.config = res.data.data;
        // 2.判断url中是否有code参数
        this.code = this.getUrlParamByName("code");
        if (this.isEmpty(this.code)) {
          console.log("无code");
          console.log("统一认证系统获取授权码地址:", this.getLoginUrl());
          this.contain = "未获取到授权码,是否跳转到统一认证系统获取授权码";
          this.$refs.alertDialog.open();
          window.open(this.getLoginUrl(), '_blank')
        } else {
          console.log("有code:", this.code);
          this.contain = "有code,是否进行登录";
          this.$refs.alertDialog.open();
        }
      });
    },
    getLoginUrl() {
      let result = this.idaas.loginUrl;
      result = result.replace("{server}", this.idaas.config.server);
      result = result.replace("{client_id}", this.idaas.config.clientId);
      const encodeUri = encodeURIComponent(this.idaas.config.redirectUri);
      result = result.replace("{redirect_uri}", encodeUri);
      return result;
    },
    getIndexUrl() {
      let result = this.idaas.indexUrl;
      result = result.replace("{index_server}", this.idaas.config.indexServer);
      return result;
    },
    handleClick() {
      window.location.href = this.getLoginUrl();
    },
    isEmpty(val) {
      if (
        val === null ||
        typeof val === "undefined" ||
        (typeof val === "string" && val === "" && val !== "undefined")
      ) {
        return true;
      }
      return false;
    },
    getUrlParamByName(name) {
      const url = window.location.href;
      return this.getUrlParamByUrlAndName(url, name);
    },
    getUrlParamByUrlAndName(url, name) {
      if (this.isEmpty(url) || url.split("?").length < 2) {
        return null;
      } else {
        // 通过 ? 分割获取后面的参数字符串
        let urlStr = url.split("?")[1];
        // 处理#号
        const endIndex = urlStr.indexOf("#");
        if (endIndex !== -1) {
          urlStr = urlStr.substring(0, endIndex);
        }
        // 创建空对象存储参数
        const obj = {};
        // 再通过 & 将每一个参数单独分割出来
        const paramsArr = urlStr.split("&");
        for (let i = 0, len = paramsArr.length; i < len; i++) {
          // 再通过 = 将每一个参数分割为 key:value 的形式
          const arr = paramsArr[i].split("=");
          obj[arr[0]] = arr[1];
        }
        return obj[name];
      }
    },
  },
};
</script>

<style lang="scss" scoped>
</style>